package com.learn.ccs;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {

    public static final int NUM = 3;

    public static void main(String[] args) {

        //信号量: 限流 使用  做并发互斥时使用
        Semaphore semaphore = new Semaphore(NUM);

        for (int i = 1; i <= 6; i++) {
            final int temp = i;
             new Thread(()->{
                 try {
                     //获取令牌
                     semaphore.acquire();
                     System.out.println(temp+"抢到车位!");
                     TimeUnit.SECONDS.sleep(2);
                     System.out.println(temp+"离开车位!");
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }finally {
                     //释放令牌
                     semaphore.release();
                 }
             },temp+"").start();
        }
    }
}
